package com.lagou.cluster.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ClassName AuthInterceptor
 * @Description 权限校验拦截器
 * @Author playboy
 * @Date 2021/5/25 8:54 下午
 * @Version 1.0
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {
	private static Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

	/**
	 * 前置操作
	 *
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//不是登录操作，就要在session中去获取用户名，如果获取到就放行，如果获取不到，就要跳转到登录页面
		System.out.println("接收到请求：" + request.getRequestURL().toString());
		HttpSession session = request.getSession();
		Object username = session.getAttribute("username");
		if (username != null) {
			//有登录信息，直接放行
			return true;
		} else {
			//无登录信息，重定向到登录页面
			response.sendRedirect(request.getContextPath() + "/toLogin");
			return false;
		}
	}
}
